﻿using System.Text;

namespace CommLib
{
    public class MessageContacts : BluetoothMessage
    {
        private readonly static char DELIMITER = '\n';

        public MessageContacts(Contact[] c)
		    : base(BtMessageType.Contacts, null)
        {
		    mData = new string[c.Length * Contact.FIELD_COUNT];

		    int i = 0;

		    foreach (Contact contact in c) {
			    mData[i++] = contact.getId().ToString();
			    mData[i++] = contact.Name;
			    mData[i++] = join(contact.getNumbers());
		    }

	    }

        public MessageContacts(byte[] data, int length)
            : base(BtMessageType.Contacts, data, length)
        {
        }

        public Contact[] getContacts()
        {
            Contact[] list = null;

            if (mData.Length % Contact.FIELD_COUNT == 0)
            {
                list = new Contact[mData.Length / Contact.FIELD_COUNT];
                string[] splits;
                int idx = 0;

                for (int i = 0; i < mData.Length; i += Contact.FIELD_COUNT)
                {
                    splits = mData[i + 2].Split(DELIMITER);

                    list[idx++] = new Contact(int.Parse(mData[i]), mData[i + 1], splits);
                }
            }

            return list;
        }

        private static string join(string[] arr)
        {
            StringBuilder b = new StringBuilder();

		    if (arr != null && arr.Length > 0) 
            {
			    foreach (string s in arr) 
                {
				    b.Append(s);
				    b.Append(DELIMITER);
			    }

			    // Letzten Delimiter entfernen
                b.Remove(b.Length - 1, 1);
		    }

		    return b.ToString();
        }
    }
}
